#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
文件清理选项卡 - 负责文件清理功能的GUI界面
"""

import os
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path

from core import cleaner
from cli import format_size

class CleanerTab(ttk.Frame):
    """文件清理选项卡"""
    
    def __init__(self, parent):
        super().__init__(parent)
        
        # 创建变量
        self.directory_var = tk.StringVar()
        self.clean_type_var = tk.StringVar(value="duplicates")
        self.recursive_var = tk.BooleanVar(value=True)
        self.find_only_var = tk.BooleanVar(value=True)
        self.keep_strategy_var = tk.StringVar(value="oldest")
        self.min_size_var = tk.StringVar(value="100")
        self.extensions_var = tk.StringVar(value="tmp,bak,log,cache")
        
        # 创建界面元素
        self.create_widgets()
        
        # 绑定事件
        self.clean_type_var.trace("w", self.on_clean_type_changed)
        self.find_only_var.trace("w", self.on_find_only_changed)
        
        # 初始状态设置
        self.on_clean_type_changed()
    
    def create_widgets(self):
        """创建界面元素"""
        # 创建主框架
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 目录选择
        dir_frame = ttk.LabelFrame(main_frame, text="目录")
        dir_frame.pack(fill=tk.X, pady=5)
        
        ttk.Entry(dir_frame, textvariable=self.directory_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        ttk.Button(dir_frame, text="浏览...", command=self.browse_directory).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 清理类型选择
        clean_type_frame = ttk.LabelFrame(main_frame, text="清理类型")
        clean_type_frame.pack(fill=tk.X, pady=5)
        
        ttk.Radiobutton(clean_type_frame, text="查找重复文件", variable=self.clean_type_var, value="duplicates").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(clean_type_frame, text="查找空文件夹", variable=self.clean_type_var, value="empty_dirs").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(clean_type_frame, text="查找临时文件", variable=self.clean_type_var, value="temp_files").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(clean_type_frame, text="查找大文件", variable=self.clean_type_var, value="large_files").pack(anchor=tk.W, padx=5, pady=2)
        
        # 基本选项
        options_frame = ttk.LabelFrame(main_frame, text="基本选项")
        options_frame.pack(fill=tk.X, pady=5)
        
        ttk.Checkbutton(options_frame, text="递归处理子目录", variable=self.recursive_var).pack(anchor=tk.W, padx=5, pady=2)
        
        self.find_only_check = ttk.Checkbutton(options_frame, text="仅查找不删除", variable=self.find_only_var)
        self.find_only_check.pack(anchor=tk.W, padx=5, pady=2)
        
        # 高级选项框架 - 根据清理类型动态显示
        self.advanced_frame = ttk.LabelFrame(main_frame, text="高级选项")
        
        # 重复文件选项
        self.duplicates_frame = ttk.Frame(self.advanced_frame)
        ttk.Label(self.duplicates_frame, text="保留策略:").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Radiobutton(self.duplicates_frame, text="最旧的", variable=self.keep_strategy_var, value="oldest").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Radiobutton(self.duplicates_frame, text="最新的", variable=self.keep_strategy_var, value="newest").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Radiobutton(self.duplicates_frame, text="第一个", variable=self.keep_strategy_var, value="first").pack(side=tk.LEFT, padx=5, pady=5)
        
        # 临时文件选项
        self.temp_files_frame = ttk.Frame(self.advanced_frame)
        ttk.Label(self.temp_files_frame, text="文件扩展名 (逗号分隔):").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Entry(self.temp_files_frame, textvariable=self.extensions_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        
        # 大文件选项
        self.large_files_frame = ttk.Frame(self.advanced_frame)
        ttk.Label(self.large_files_frame, text="最小文件大小 (MB):").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Entry(self.large_files_frame, textvariable=self.min_size_var, width=10).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 执行按钮和进度区
        action_frame = ttk.Frame(main_frame)
        action_frame.pack(fill=tk.X, pady=10)
        
        self.progress_var = tk.StringVar(value="")
        ttk.Label(action_frame, textvariable=self.progress_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        
        self.action_button = ttk.Button(action_frame, text="查找", command=self.clean_files)
        self.action_button.pack(side=tk.RIGHT, padx=5)
        
        # 结果显示区域
        results_frame = ttk.LabelFrame(main_frame, text="查找结果")
        results_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.results_text = tk.Text(results_frame, wrap=tk.WORD, height=10)
        self.results_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        scrollbar = ttk.Scrollbar(self.results_text, command=self.results_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.results_text.config(yscrollcommand=scrollbar.set)
        self.results_text.config(state=tk.DISABLED)
    
    def on_clean_type_changed(self, *args):
        """清理类型变化时的处理"""
        clean_type = self.clean_type_var.get()
        
        # 更新操作按钮文本
        self.update_action_button()
        
        # 隐藏所有高级选项
        self.advanced_frame.pack_forget()
        if hasattr(self, 'duplicates_frame'):
            self.duplicates_frame.pack_forget()
        if hasattr(self, 'temp_files_frame'):
            self.temp_files_frame.pack_forget()
        if hasattr(self, 'large_files_frame'):
            self.large_files_frame.pack_forget()
        
        # 显示相应的高级选项
        if clean_type in ["duplicates", "empty_dirs", "temp_files"]:
            # 这些类型可以删除，启用find_only选项
            self.find_only_check.config(state=tk.NORMAL)
        else:
            # 大文件只能查找，禁用find_only选项
            self.find_only_check.config(state=tk.DISABLED)
            self.find_only_var.set(True)
        
        if clean_type == "duplicates":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.duplicates_frame.pack(fill=tk.X, padx=5, pady=5)
        elif clean_type == "temp_files":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.temp_files_frame.pack(fill=tk.X, padx=5, pady=5)
        elif clean_type == "large_files":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.large_files_frame.pack(fill=tk.X, padx=5, pady=5)
    
    def on_find_only_changed(self, *args):
        """查找/删除模式变化时的处理"""
        self.update_action_button()
    
    def update_action_button(self):
        """更新操作按钮文本"""
        if self.find_only_var.get():
            self.action_button.config(text="查找")
        else:
            self.action_button.config(text="删除")
    
    def browse_directory(self):
        """浏览选择目录"""
        directory = filedialog.askdirectory(title="选择目录")
        if directory:
            self.directory_var.set(directory)
    
    def clean_files(self):
        """执行文件清理"""
        # 获取参数
        directory = self.directory_var.get()
        clean_type = self.clean_type_var.get()
        recursive = self.recursive_var.get()
        find_only = self.find_only_var.get()
        
        # 验证目录
        if not directory:
            messagebox.showerror("错误", "请选择目录")
            return
        
        if not os.path.exists(directory) or not os.path.isdir(directory):
            messagebox.showerror("错误", f"目录不存在或不是一个有效的目录: {directory}")
            return
        
        # 清空结果区域
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.config(state=tk.DISABLED)
        
        # 更新进度显示
        action_text = "查找中" if find_only else "删除中"
        self.progress_var.set(f"{action_text}...")
        
        # 获取特定选项
        keep_strategy = self.keep_strategy_var.get() if clean_type == "duplicates" else None
        extensions = self.extensions_var.get().split(',') if clean_type == "temp_files" else None
        
        try:
            min_size = int(self.min_size_var.get()) * 1024 * 1024  # 转换为字节
        except ValueError:
            min_size = 100 * 1024 * 1024  # 默认100MB
        
        # 在线程中执行文件清理
        threading.Thread(target=self._clean_files_thread, args=(
            directory, clean_type, recursive, find_only, keep_strategy, extensions, min_size
        )).start()
    
    def _clean_files_thread(self, directory, clean_type, recursive, find_only, keep_strategy, extensions, min_size):
        """在线程中执行文件清理"""
        try:
            results = None
            
            # 查找阶段
            if clean_type == "duplicates":
                duplicates = cleaner.find_duplicates(directory, recursive)
                
                if duplicates:
                    if not find_only:
                        deleted = cleaner.remove_duplicates(duplicates, keep_strategy)
                        self.show_duplicates_results(duplicates, deleted)
                    else:
                        self.show_duplicates_results(duplicates)
                else:
                    self.show_empty_results("重复文件")
            
            elif clean_type == "empty_dirs":
                empty_dirs = cleaner.find_empty_dirs(directory, recursive)
                
                if empty_dirs:
                    if not find_only:
                        deleted = cleaner.remove_empty_dirs(directory, recursive)
                        self.show_empty_dirs_results(empty_dirs, deleted)
                    else:
                        self.show_empty_dirs_results(empty_dirs)
                else:
                    self.show_empty_results("空文件夹")
            
            elif clean_type == "temp_files":
                temp_files = cleaner.find_temp_files(directory, recursive, extensions)
                
                if temp_files:
                    if not find_only:
                        deleted = cleaner.remove_temp_files(directory, recursive, extensions)
                        self.show_temp_files_results(temp_files, deleted)
                    else:
                        self.show_temp_files_results(temp_files)
                else:
                    self.show_empty_results("临时文件")
            
            elif clean_type == "large_files":
                large_files = cleaner.find_large_files(directory, min_size, recursive)
                
                if large_files:
                    self.show_large_files_results(large_files)
                else:
                    self.show_empty_results(f"大于 {format_size(min_size)} 的文件")
            
            # 更新进度显示
            action_text = "查找" if find_only else "清理"
            self.progress_var.set(f"{action_text}完成")
            
        except Exception as e:
            # 更新进度显示
            self.progress_var.set("操作出错")
            
            # 显示错误消息
            messagebox.showerror("错误", f"执行操作时出错: {str(e)}")
    
    def show_empty_results(self, item_type):
        """显示空结果信息"""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.insert(tk.END, f"未找到{item_type}")
        self.results_text.config(state=tk.DISABLED)
    
    def show_duplicates_results(self, duplicates, deleted=None):
        """显示重复文件结果"""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        total_groups = len(duplicates)
        total_files = sum(len(files) - 1 for files in duplicates.values())
        total_size = sum(p.stat().st_size * (len(files) - 1) for hash_val, files in duplicates.items() for p in files if len(files) > 0)
        
        if deleted:
            deleted_count = sum(len(files) for files in deleted.values())
            self.results_text.insert(tk.END, f"已删除 {deleted_count} 个重复文件（共节省: {format_size(total_size)}）\n\n")
        else:
            self.results_text.insert(tk.END, f"找到 {total_groups} 组重复文件，共 {total_files} 个可删除的文件（大小: {format_size(total_size)}）\n\n")
        
        # 显示前10组
        count = 0
        for hash_val, files in duplicates.items():
            if count >= 10:
                self.results_text.insert(tk.END, f"\n... 还有 {total_groups - 10} 组未显示")
                break
                
            file_size = files[0].stat().st_size if files else 0
            self.results_text.insert(tk.END, f"重复组 {count+1} (大小: {format_size(file_size)}):\n")
            
            for i, file_path in enumerate(files):
                if deleted:
                    prefix = "  [保留]" if str(file_path) not in [str(f) for group in deleted.values() for f in group] else "  [删除]"
                else:
                    prefix = "  [保留]" if i == 0 else "  [可删除]"
                    
                self.results_text.insert(tk.END, f"{prefix} {file_path}\n")
            
            self.results_text.insert(tk.END, "\n")
            count += 1
        
        self.results_text.config(state=tk.DISABLED)
    
    def show_empty_dirs_results(self, empty_dirs, deleted=None):
        """显示空文件夹结果"""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        if deleted:
            self.results_text.insert(tk.END, f"已删除 {len(deleted)} 个空文件夹\n\n")
        else:
            self.results_text.insert(tk.END, f"找到 {len(empty_dirs)} 个空文件夹\n\n")
        
        # 显示前20个
        for i, dir_path in enumerate(empty_dirs):
            if i >= 20:
                self.results_text.insert(tk.END, f"\n... 还有 {len(empty_dirs) - 20} 个未显示")
                break
                
            self.results_text.insert(tk.END, f"  {dir_path}\n")
        
        self.results_text.config(state=tk.DISABLED)
    
    def show_temp_files_results(self, temp_files, deleted=None):
        """显示临时文件结果"""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        total_size = sum(p.stat().st_size for p in temp_files)
        
        if deleted:
            self.results_text.insert(tk.END, f"已删除 {len(deleted)} 个临时文件（共节省: {format_size(total_size)}）\n\n")
        else:
            self.results_text.insert(tk.END, f"找到 {len(temp_files)} 个临时文件（大小: {format_size(total_size)}）\n\n")
        
        # 显示前20个
        for i, file_path in enumerate(temp_files):
            if i >= 20:
                self.results_text.insert(tk.END, f"\n... 还有 {len(temp_files) - 20} 个未显示")
                break
                
            file_size = file_path.stat().st_size
            self.results_text.insert(tk.END, f"  {file_path} ({format_size(file_size)})\n")
        
        self.results_text.config(state=tk.DISABLED)
    
    def show_large_files_results(self, large_files):
        """显示大文件结果"""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        total_size = sum(size for _, size in large_files)
        
        self.results_text.insert(tk.END, f"找到 {len(large_files)} 个大文件（总大小: {format_size(total_size)}）\n\n")
        
        # 显示前20个
        for i, (file_path, size) in enumerate(large_files):
            if i >= 20:
                self.results_text.insert(tk.END, f"\n... 还有 {len(large_files) - 20} 个未显示")
                break
                
            self.results_text.insert(tk.END, f"  {file_path} ({format_size(size)})\n")
        
        self.results_text.config(state=tk.DISABLED) 